package com.system.common.controller.image;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.system.common.constant.SessionKeyConst;
import com.system.common.service.image.ImageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;


@Controller
@RequestMapping("/image")
public class ImageController {

    private static final Logger logger = LoggerFactory.getLogger(ImageController.class);
    private static final String IMAGE_TYPE = "JPEG";


    @Autowired
    private ImageService imageService;


    /**
     * 生成随机图片
     */
    @RequestMapping(value = "/getRandCode", method = RequestMethod.GET)
    public void getRandCode(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        StringBuilder codeBuilder = new StringBuilder();
        BufferedImage image = imageService.buildImage(codeBuilder);
        session.removeAttribute(SessionKeyConst.CAPTCHA_ADMIN_KEY);
        session.setAttribute(SessionKeyConst.CAPTCHA_ADMIN_KEY, codeBuilder.toString());
        try {
            // 将内存中的图片通过流动形式输出到客户端
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
            encoder.encode(image);
        } catch (Exception e) {
            logger.error("获取图片验证码异常", e);
        }
    }
}

